<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class JAJobBoardModelJACoupon extends JModel
{
	
	var $_data;
	var $cate;
	var $_table;
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
		$this->cate =null;
	}
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}


	function &getItem()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__ja_coupon '.
					'  WHERE id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();			
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->name = '';
			$this->_data->coupons_count = '1';
			$this->_data->coupon_usage_count = '1';
			$this->_data->member_coupon_usage_count = '1';
			$this->_data->discount = '10';
			$this->_data->discount_type = '%';
			$this->_data->limit_date = '1';
			$this->_data->begin_date = date("Y-m-d H:i:s");
			$this->_data->end_date = date("Y-m-d H:i:s");
			$this->_data->posting_plan = '';
			$this->_data->description = '';
			$this->_data->published = '';			
		}
		return $this->_data;
	}
	
	function &getTable(){
		 if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_Coupon', 'JobBoardTable');
		}
		return $this->_table;
	}
	// get all categories for parrent cat
	// save a category when edit or new.
	function store()	{		
		$db		 =& JFactory::getDBO();
		$post	= JRequest::get( 'post' );
		
		$posting_plan = JRequest::getVar('posting_plan',  "", '', 'array');
		if ( isset($posting_plan[0]) && $posting_plan[0] != 0 ){
		    $post['posting_plan'] = implode(",", $posting_plan);		    
		}
		
		$row =& $this->getTable();
		
		if (!$row->bind($post)) {
			$this->setError(JText::_("Invalid info"));
			return  false;
			
		}
		// Make sure the hello record is valid
		if (!$row->check()) {
			$this->setError(JText::_("Invalid info"));
			return false;
		}
		if (!$row->store()) 
		{
			$this->setError( JText::_("Invalid info") );
		}					
		
		// Create coupon code
		$cids = JRequest::getVar('cid',  0, '', 'array');
		if ( isset($cids[0]) && $cids[0] != 0 ){
		    $cids = $cids[0];
		}else $cids=0;
	
		$db =& JFactory::getDBO();
		
		/*$query = "DELETE FROM #__ja_coupon_code WHERE coupon_id = '".$cids."' ";
		$db->setQuery($query);
		$db->query();*/
		
		if( $cids == 0 ){
		    $coupons_count = JRequest::getVar("coupons_count", "0");		    
		    for ($i=0; $i<$coupons_count; $i++){
                $code = $this->getCode();
                $query = "INSERT INTO #__ja_coupon_code(coupon_id, code, count, used) VALUES(
                            '".$row->id."',
                            '".$code."',
                            '".JRequest::getVar("coupon_usage_count", "1")."',
                            '0' )";
                $db->setQuery($query);
                $db->query();
		    }
		}
		
		return $row->id;
	}
	
	// Get unique code
	function getCode(){
	    $db =& JFactory::getDBO();
	    $code_length  = JRequest::getVar("code_length", "1");
	    $unique = $this->random_letters($code_length);        
        $query = "SELECT id FROM #__ja_coupon_code WHERE code = '".$unique."' ";
        $db->setQuery($query);
        $result = $db->loadResult();
        if( $result )
            return $this->getCode();
        else return $unique;
	}
	
	function random_letters ($numofletters) {
	    $vercode = "";
        if (!isset($numofletters)) 
            $numofletters = 10; // if $numofletters is not specified sets to 10 letters
        $literki = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'W', 'Z');
        $ilosc_literek = count($literki);
        for ($licz = 0; $licz < $numofletters; $licz++) {
            $rand = rand(0, $ilosc_literek-1);
            $vercode = $vercode.$literki[$rand];
        }
        return $vercode;
    } 
	
	function getListCode(){
	    $db =& JFactory::getDBO();
	    $cids = JRequest::getVar('cid',  0, '', 'array');
	    if ( isset($cids[0]) && $cids[0] != 0 ){
		    $cids = $cids[0];
		}else $cids=0;
		
		$query = "SELECT * FROM #__ja_coupon_code WHERE coupon_id = '".$cids."' ";
		$db->setQuery($query);
		$result = $db->loadObjectList();
		
		return $result;
	}
	
	function getCodeItem(){
	    $db =& JFactory::getDBO();
	    $id = JRequest::getVar('code_id', 0);
	    		
		$query = "SELECT * FROM #__ja_coupon_code WHERE id = '".$id."' ";
		$db->setQuery($query);
		$result = $db->loadObject();
		
		return $result;
	}
	
	function get_total_codes($couponid){
		$db =& JFactory::getDBO();
	    		
		$query = "SELECT COUNT(id) FROM #__ja_coupon_code WHERE coupon_id='".(int)$couponid."' ";
		$db->setQuery($query);
		return $db->loadResult();		
	}
	
	function get_count_codes($couponid){
		$db =& JFactory::getDBO();
	    		
		$query = "SELECT SUM(count) as number FROM #__ja_coupon_code WHERE coupon_id='".(int)$couponid."' ";
		$db->setQuery($query);
		return $db->loadResult();		
	}
	
	function get_usage_codes($couponid){
		$db =& JFactory::getDBO();
	    		
		$query = "SELECT SUM(used) as number FROM #__ja_coupon_code WHERE coupon_id='".(int)$couponid."' ";
		$db->setQuery($query);
		return $db->loadResult();		
	}
	
	// method delete one or more categories selected
	function delete()
	{
	    $db	=& JFactory::getDBO();
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		JArrayHelper::toInteger($cids, array(0));
		$row =& $this->getTable();

		if (count( $cids ))
		{
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );                    				
					return false;
				}
				$db->setQuery("DELETE FROM #__ja_coupon_code WHERE coupon_id = ".$cid."");                    
                $result = $db->query();	
			}						
		}
		return true;
	}
	
	
	// method delete one or more categories selected
	function delete_code()
	{
	    $db	=& JFactory::getDBO();
		$id = JRequest::getVar( 'code_id', '0');
        $db->setQuery("DELETE FROM #__ja_coupon_code WHERE id = ".$id."");
        
        $result = $db->query();
        return $result;
    }
    
    // method delete one or more categories selected
	function save_code()
	{
	    $db	=& JFactory::getDBO();
		$id = JRequest::getVar( 'id', '0');
        
		// Check code
		$db->setQuery("SELECT id FROM #__ja_coupon_code WHERE code = '".JRequest::getVar("code", "")."' AND id != '".$id."' ");		
        $result = $db->loadRow();
        if( $result ){
            return false;
        }
        
        $db->setQuery("UPDATE #__ja_coupon_code SET code = '".JRequest::getVar("code", "")."',
                        count = '".JRequest::getVar("count", "")."',
                        used = '".JRequest::getVar("used", "")."' 
                        WHERE id = '".$id."'");
        $result = $db->query();
               
        return $result;
    }
	
	function getcountcredit()
	{
		$db	=& JFactory::getDBO();
		$param = $this->getvar();
		$filter_order	= $param['filter_order'];
		$filter_order_Dir	= $param['filter_order_Dir']; 
		$search		= $param['search'];
		$search	= JString::strtolower( $search );
		$where = '  WHERE 1 ';
		$filter ='';
		if ($search) {
			$filter = ' AND LOWER(s.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
			}
		$query = 'SELECT COUNT(*)'
            	. ' FROM #__ja_coupon s'
            	;
		$query .=$where .$filter;
		$db->setQuery( $query );
		$total = $db->loadResult();
		return $total;
		
	}
	
	function getvar()
	{
		global $mainframe, $option;
		$list = array();
		$list['filter_order'] 		= JRequest::getVar('filter_order', 's.id');
		$list['filter_order_Dir'] 	= $mainframe->getUserStateFromRequest( $option.'.jacoupon.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$list['limit'] 		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$list['limitstart'] 	= $mainframe->getUserStateFromRequest( $option.'.jacoupon.limitstart', 'limitstart', 0, 'int' );
		$list['search'] 	= $mainframe->getUserStateFromRequest( $option.'.jacoupon.search',						'search',			'',				'string' );
		$list['option'] 	= $option;
		return  $list;
	}
	
	// get all subscriptions
	function getItems()
	{
		// Lets load the data if it doesn't already exist
		$db	=& JFactory::getDBO();
		$param = $this->getvar();
		$filter_order	= $param['filter_order'];
		$filter_order_Dir	= $param['filter_order_Dir']; 
		$limit		= $param['limit'];
		$limitstart	= $param['limitstart']; 
		$search		= $param['search'];
		$search	= JString::strtolower( $search );
		$filter ='';
		if ($search) {
			$filter = ' WHERE LOWER(s.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}
		$total = $this->getcountcredit();
		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );
		$order 			= ' ORDER BY  '. $filter_order .' '. $filter_order_Dir ;
		$query = 'SELECT  s.* FROM #__ja_coupon AS s '
				.$filter. $order
				;
		
		$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
		$rows = $db->loadObjectList();
		for ($i=0;$i<count($rows);$i++)
			if (isset($rows[$i]->title))
			{
				$rows[$i]->title = JFilterInput::_decode($rows[$i]->title);
				$rows[$i]->title = JFilterInput::clean($rows[$i]->title);
			}
		return $rows;
	}
	
	// published categories
	function dopublish( $publish =1, $field='published')
	{
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());
		JArrayHelper::toInteger($cid, array(0));
		$ids = implode( ',', $ids );
		
		$query = "UPDATE #__ja_coupon"
		. "\n SET $field = " . intval( $publish )
		. "\n WHERE id IN ( $ids )"
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}
}
